package com.example.mvvmtest.viewModel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mvvmtest.Repository.UserRepository
import com.example.mvvmtest.model.entity.User
import kotlinx.coroutines.launch

class MainActivityViewModel(
    private val userId: String,
    override val userRepository: UserRepository
) : UserViewModel(userRepository) {

    // 用户信息
    private val _userInfo = MutableLiveData(User(id = userId, password = ""))
    val userInfo: LiveData<User> = _userInfo

    // 状态
    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _message = MutableLiveData("")
    val message: LiveData<String> = _message

    init {
        // 加载用户信息
        loadUserInfo()
    }

    // 加载用户信息
    private fun loadUserInfo() {
        viewModelScope.launch {
            userRepository.getUserInfo(userId).collect { user ->
                user?.let { _userInfo.value = it }
            }
        }
    }

    // 更新用户信息
    fun updateInfo(newPassword: String, newAgeStr: String, newJob: String) {
        _message.value = ""
        val newAge = newAgeStr.toIntOrNull()

        // 验证
        if (newPassword.isNotEmpty() && !isPasswordValid(newPassword)) {
            _message.value = "新密码格式不正确"
            return
        }
        if (newAgeStr.isNotEmpty() && newAge == null) {
            _message.value = "年龄必须是数字"
            return
        }

        viewModelScope.launch {
            _isLoading.value = true
            try {
                // 逐一更新（非空才更新）
                if (newPassword.isNotEmpty()) {
                    userRepository.updatePassword(userId, newPassword)
                }
                if (newAge != null) {
                    userRepository.updateAge(userId, newAge)
                }
                if (newJob.isNotEmpty()) {
                    userRepository.updateJob(userId, newJob)
                }
                _message.value = "更新成功"
            } catch (e: Exception) {
                _message.value = "更新失败: ${e.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }
}